﻿using AutoMapper;
using B.S.AuthCenter.Api.Write.Application.Command.Users;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.AuthCenter.Api.Write.Application.Handler.Users
{
    public class UpdateUsersHandler : IRequestHandler<UpdateUsersCommand, ApiResult<int>>
    {
        IBaseRepository<UserModel> UserRepo;
       
        IMapper mapper;
        IBaseRepository<LogModel> logRepo;

        public UpdateUsersHandler(IBaseRepository<UserModel> userRepo, IMapper mapper, IBaseRepository<LogModel> logRepo)
        {
            this.UserRepo = userRepo;
           
            this.mapper = mapper;
            this.logRepo = logRepo;
        }

        public Task<ApiResult<int>> Handle(UpdateUsersCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var users = UserRepo.GetAll().Where(c => c.Id == request.Id).FirstOrDefault();
            if (users ==null)
            {
                
                res.Msg = "用户不存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            var userss = UserRepo.GetAll().Where(c => c.UserName == request.UserName && c.Id!=request.Id).Count();
            if (userss > 0)
            {
               
                res.Msg = "用户名不能重复";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            users.Updator = request.Updator;
            users.UpdatorDate = DateTime.Now;
            users = mapper.Map(request,users);
            LogModel logModel = new LogModel()
            {
                LogContent = "账户修改",
                Creator=users.UserName,
                CreatorDate=DateTime.Now,
                Updator = request.UserName,
                UpdatorDate = DateTime.Now,
            };
            int a = 0;
            int b = 0;
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                a = UserRepo.Update(users).Result;
                b = logRepo.Update(logModel).Result;
                tran.Complete();
            }
            if (a > 0)
            {
               
                res.Code = ApiEnum.Success;
                res.Msg = "修改用户信息成功";
                res.Datas = a;
                return Task.FromResult(res);
            }
            else
            {
               
                res.Code = ApiEnum.Fail;
                res.Msg = "修改用户信息失败";
                res.Datas = a;
                return Task.FromResult(res);
            }
        }
    }
}
